/* global AMap */
import React from "react";
import "./index.scss";

export default class Map extends React.Component {
	constructor(props) {
		super(props);
		this.map = null;
		this.overlayGroup = null;
		this.cluster = null;
	}
  
	componentDidMount() {
		this.initMap();
	}
	componentWillUpdate() {
		
	}
  
	initMap() {
		const { points } = this.props;
		this.map = new AMap.Map("aMap", {
			resizeEnable: true, // 是否监控地图容器尺寸变化
			zoom: 11, // 初始化地图层级
			center: [108.948063, 34.259067], // 初始化地图中心点
			mapStyle: "amap://styles/grey"
		});
		if(points.length > 10) {
			this.addCluster(points);
		}else{
			this.addPoint(points);
		}
	}
  
	pointsToMarkers(points) {
		const markers = [];
		points.forEach(item => {
			const marker = new AMap.Marker({
				position: new AMap.LngLat(item.lng, item.lat),
				icon: "https://static.justdodo.cn/xiaohan/38c2b6dda19064af5c7806fbf266fafd2d5dd73a.svg",
				offset: new AMap.Pixel(-13, -30),
				extData: {id: item._id}
			});
			marker.setLabel({
				offset: new AMap.Pixel(40, 20),
				content: `<div class='info'>${item.title}</div>`
			});
			markers.push(marker);
		});
		return markers;
	}
  
	addPoint(points) {
		const markers = this.pointsToMarkers(points);
		if (this.overlayGroup) {
			this.map.remove(this.overlayGroup);
		}
		this.overlayGroup = new AMap.OverlayGroup(markers);
		this.map.add(this.overlayGroup);
	}

	addCluster(points) {
		if (this.cluster) {
			this.cluster.setMap(null);
		}
		const markers = this.pointsToMarkers(points);
		this.cluster = new AMap.MarkerClusterer(this.map, markers, {gridSize: 50});
	}
  
	render() {
		return (
			<div className="map-container">
				<div id="aMap"></div>
			</div>
		);}

}

